const cluster = require('cluster');
const downloadFile = require('./download')
const tsBaseUrl = 'https://yanzishan.shuhu-zuida.com/20190901/16323_2ecf24f2/1000k/hls/'

let tsArr = [
    'fb547ee3e66000000.ts',
    'fb547ee3e66000001.ts',
    'fb547ee3e66000002.ts',
    'fb547ee3e66000003.ts',
    'fb547ee3e66000004.ts',
    'fb547ee3e66000005.ts',
    'fb547ee3e66000006.ts',
    'fb547ee3e66000007.ts',
    'fb547ee3e66000008.ts'
]
let start = 0
function aa() {
    const worker = cluster.fork();
    let ts = tsArr.shift()
    console.log('seqArr.length:', tsArr.length)
    console.log('ts:', ts);
    worker.send(ts)
    worker.on('message', function (msg) {
        worker.disconnect()
        if (tsArr.length > 0) {
            aa()
        }
    })
}
function downlodTs() {
    if (cluster.isMaster) {
        start = Date.now()
        for (let i = 0; i < 8; i++) {
            aa()
        }
        cluster.on('disconnect', function () {
            const endTime = Date.now()
            console.log((endTime - start) / 1000 + 's')
        })
    } else if (cluster.isWorker){
        process.on('message', seq => {
            console.log(`[Worker]# starts calculating... seq: ${seq}`)
            downloadFile(tsBaseUrl+seq, seq, function() {
                process.send('My task has ended.')
                // process.kill(process.pid);
            })
        })
    }
}

downlodTs()